package com.example.xiaohu.modules.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.xiaohu.config.minio.MinioProperties;
import com.example.xiaohu.modules.entity.FileStorage;
import com.example.xiaohu.modules.mapper.FileStorageMapper;
import com.example.xiaohu.modules.service.FileStorageService;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.http.Method;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLDecoder;

@Slf4j
@Service
public class FileStorageImpl extends ServiceImpl<FileStorageMapper, FileStorage> implements FileStorageService {

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    @Override
    @SneakyThrows
    public String uploadFile(MultipartFile file,String uid) {
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(uid+"_"+file.getOriginalFilename())
                .contentType(file.getContentType())
                .stream(file.getInputStream(), file.getSize(), -1)
                .build();
        log.info("==============="+file.getSize()+"===============");
        minioClient.putObject(putObjectArgs);
        GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(minioProperties.getBucketName())
                .object(uid+"_"+file.getOriginalFilename())
                .build();
        String fileUrl = minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
        return URLDecoder.decode(fileUrl,"UTF-8");
    }

    @Override
    @SneakyThrows
    public void deleteMinioFile(FileStorage fileStorage){
        try{
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileStorage.getId()+"_"+fileStorage.getFileName()).build());
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}
